package com.zwx.linkList.leetcode_6;

/**
 * 环形链表
 * <p>
 * 给定一个链表，判断链表中是否有环。
 *
 * @author 文希
 * @create 2019-07-03 23:01
 */
public class HasCycle {

    /**
     * 思路：
     * 设置快慢指针，当快指针追上慢指针时，即出现环
     */
    private static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        ListNode listNode6 = new ListNode(4, null);
        ListNode listNode5 = new ListNode(3, listNode6);
        ListNode listNode4 = new ListNode(1, listNode5);

        ListNode listNode3 = new ListNode(3, listNode4);
        ListNode listNode2 = new ListNode(2, listNode3);
        ListNode listNode1 = new ListNode(1, listNode2);

        boolean b = hasCycle(listNode1);
        System.out.println("b = " + b);

    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
